import React, { useEffect, useState, useCallback } from 'react';
import { Table, Card, message, Button, Form, Tabs, Input, Select, DatePicker } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table';
import { AbilityItem, OrganizationItem } from 'admin/schema/Cas';
import {
  getAbilities,
  getCasOrganizationsShow,
  addAbility,
  auditAbility,
  getAbilityApplication,
} from 'admin/servers/modules/Cas';
import AbilityFormModal from '../components/AbilityFormModal';
import AbilityAuditModal from '../components/AbilityAuditModal';
import { useSelector } from 'react-redux';
import { debounce, flatten, includes, isEmpty, map, reduce, some, startsWith } from 'lodash';
import qs from 'query-string';

const { TabPane } = Tabs;

const Abilities: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [abilities, setAbilities] = useState<AbilityItem[]>([]);
  const [organizations, setOrganizations] = useState<
    Omit<OrganizationItem, 'children' | 'description'>[]
  >([]);
  const [activeTab, setActiveTab] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [auditModalVisible, setAuditModalVisible] = useState(false);
  const [selectedAbility, setSelectedAbility] = useState<AbilityItem | null>(null);
  const [abilityType, setAbilityType] = useState<string[]>([]);
  const [form] = Form.useForm();
  const [auditForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchForm] = Form.useForm();

  const userInfo = useSelector((state: any) => state.loginInfo);

  // 获取能力列表
  const fetchAbilities = useCallback(
    async (page = 1, pageSize = 10, params = {}) => {
      setLoading(true);
      try {
        if (!activeTab) return;
        const response = await getAbilities({
          pageNo: page - 1,
          pageSize,
          type: activeTab,
          year: params.year ? params.year.format('YYYY') : undefined,
          status: params.status,
        });
        if (response.status === 200) {
          const { content, totalElements, number } = response.data;
          setAbilities(content);
          setPagination(prev => ({
            ...prev,
            pageSize,
            current: number + 1,
            total: totalElements,
          }));
        }
      } catch (error) {
        console.error('获取能力列表出错:', error);
        message.error('获取能力列表失败');
      } finally {
        setLoading(false);
      }
    },
    [activeTab]
  );

  useEffect(() => {
    getCasOrganizationsShow().then(response => {
      if (response.status === 200) {
        setOrganizations(response.data);
      }
    });
    getAbilityApplication().then(response => {
      if (response.status === '200') {
        const { data } = response;
        setAbilityType(data);
        const query = qs.parse(location.search);
        if (query.activeTab && includes(data, query.activeTab)) {
          setActiveTab(query.activeTab as string);
        } else {
          setActiveTab(data[0]);
        }
      }
    });
  }, []);

  useEffect(() => {
    fetchAbilities();
  }, [fetchAbilities]);

  const handleTableChange = useCallback(
    (newPagination: TablePaginationConfig) => {
      fetchAbilities(newPagination.current, newPagination.pageSize, searchForm.getFieldsValue());
    },
    [fetchAbilities, searchForm]
  );

  // 根据单位ID获取单位名称
  const getOrgName = useCallback(
    (orgId: string) => {
      const org = organizations.find(org => org.id === orgId);
      return org ? org.name : orgId;
    },
    [organizations]
  );

  const handleAdd = useCallback(() => {
    form.resetFields();
    setModalVisible(true);
  }, [form]);

  const handleModalOk = useCallback(
    debounce(async () => {
      try {
        const values = await form.validateFields();
        const fileFields = ['materials'];
        const fileValues: any = reduce(
          fileFields,
          (acc, file) => {
            acc[file] = JSON.stringify(
              flatten(
                map(values[file], (item: any) => {
                  if (item.status === 'done' && item.response.status === 200) {
                    return item.response.data;
                  }
                  return [];
                }).filter((item: any) => !isEmpty(item))
              )
            );
            return acc;
          },
          {}
        );

        if (some(fileValues, (value: any) => value === '[]' || value === '""')) {
          message.error('请上传所有必需的文件');
          return;
        }

        const response = await addAbility({
          ...values,
          materials: fileValues.materials,
          unit: values.type === '行业短信' || values.type === '靶向短信' ? '条' : '分钟',
          threshold: values.threshold / 100,
          year: values.year.format('YYYY'),
        });

        if (response.status === 200) {
          message.success('创建成功');
          setModalVisible(false);
          fetchAbilities();
        }
      } catch (error) {
        console.error('创建能力出错:', error);
        message.error('创建失败，请检查表单');
      }
    }, 500),
    [form, fetchAbilities]
  );

  const handleAudit = useCallback(
    (record: AbilityItem) => {
      setSelectedAbility(record);
      auditForm.resetFields();
      setAuditModalVisible(true);
    },
    [auditForm]
  );

  const handleView = useCallback((record: AbilityItem) => {
    setSelectedAbility(record);
    setAuditModalVisible(true);
  }, []);

  const handleAuditOk = useCallback(
    debounce(async () => {
      if (!selectedAbility) return;
      try {
        const values = await auditForm.validateFields();
        const response = await auditAbility(selectedAbility.id, {
          ...values,
          auditBy: userInfo.id,
        });

        if (response.status === 200) {
          message.success('审核成功');
          setAuditModalVisible(false);
          fetchAbilities(pagination.current, pagination.pageSize, searchForm.getFieldsValue());
        }
      } catch (error) {
        console.error('审核出错:', error);
        message.error('审核失败，请检查表单');
      }
    }, 500),
    [selectedAbility, auditForm, userInfo.id, fetchAbilities, pagination, searchForm]
  );

  const handleReset = debounce(() => {
    searchForm.resetFields();
    fetchAbilities(1, 10, {});
  }, 500);

  const handleFinish = debounce((values: any) => {
    fetchAbilities(1, 10, values);
  }, 500);

  const handleTabChange = (key: string) => {
    const url = new URL(location.href);
    url.searchParams.set('activeTab', key);
    history.pushState({}, '', url.toString());
    setActiveTab(key);
    setPagination(prev => ({ ...prev, current: 1 }));
    searchForm.resetFields();
  };

  const columns: ColumnsType<AbilityItem> = [
    {
      title: '单位',
      dataIndex: 'org',
      key: 'org',
      render: (_, record) => getOrgName(record.org),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '年份',
      dataIndex: 'year',
      key: 'year',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (_, record) => {
        if (record.type === '行业短信' || record.type === '靶向短信') {
          return `${record.quantity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')}条`;
        } else if (record.type === '智能外呼') {
          return `${record.quantity}分钟`;
        }
      },
    },
    {
      title: '阈值',
      dataIndex: 'threshold',
      key: 'threshold',
      render: (_, record) => `${record.threshold * 100}%`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        if (record.status === 'PENDING') {
          return '待审核';
        } else if (record.status === 'UNDER_REVIEW') {
          return '审核中';
        } else if (record.status === 'APPROVED') {
          return '审核通过';
        } else if (record.status === 'REJECTED') {
          return '审核驳回';
        }
        return record.status;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      key: 'applyTime',
      render: time => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        if (record.status === 'APPROVED' || record.status === 'REJECTED') {
          return (
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          );
        }
        if (record.status === 'PENDING') {
          if (
            some(userInfo?.permissions, permission =>
              startsWith(permission?.code, 'CAPABILITY_AUDIT_CAPABILITY_AUDIT_LEVEL1')
            )
          ) {
            return (
              <Button type="link" onClick={() => handleAudit(record)}>
                审核
              </Button>
            );
          } else {
            return (
              <Button type="link" onClick={() => handleView(record)}>
                查看
              </Button>
            );
          }
        }
        if (record.status === 'UNDER_REVIEW') {
          if (
            some(userInfo?.permissions, permission =>
              startsWith(permission?.code, 'CAPABILITY_AUDIT_CAPABILITY_AUDIT_LEVEL2')
            )
          ) {
            return (
              <Button type="link" onClick={() => handleAudit(record)}>
                审核
              </Button>
            );
          } else {
            return (
              <Button type="link" onClick={() => handleView(record)}>
                查看
              </Button>
            );
          }
        }
      },
    },
  ];

  const tabPaneContent = () => {
    return (
      <>
        <Form
          layout="inline"
          form={searchForm}
          onFinish={handleFinish}
          style={{ marginBottom: '20px' }}
        >
          <Form.Item label="年份" name="year">
            <DatePicker picker="year" placeholder="请选择年份" />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select placeholder="请选择状态" allowClear>
              <Select.Option value="PENDING">待审核</Select.Option>
              <Select.Option value="UNDER_REVIEW">审核中</Select.Option>
              <Select.Option value="APPROVED">审核通过</Select.Option>
              <Select.Option value="REJECTED">审核驳回</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <Table
          columns={columns}
          dataSource={abilities}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showTotal: (total: number) => `共 ${total} 条`,
            showSizeChanger: true,
          }}
          onChange={handleTableChange}
        />
      </>
    );
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title="能力申请"
        bordered={false}
        bodyStyle={{ paddingTop: 5 }}
        extra={
          some(userInfo?.permissions, permission =>
            startsWith(permission?.code, 'CAPABILITY_AUDIT_APPLICATION')
          ) && (
            <Button type="primary" onClick={handleAdd}>
              新增能力
            </Button>
          )
        }
      >
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          {map(abilityType, item => (
            <TabPane tab={item} key={item}>
              {tabPaneContent()}
            </TabPane>
          ))}
        </Tabs>
      </Card>

      <AbilityFormModal
        visible={modalVisible}
        title="新增能力"
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        form={form}
        abilityType={abilityType}
        orgTree={organizations}
      />

      <AbilityAuditModal
        visible={auditModalVisible}
        organizations={organizations}
        title="能力详情"
        onOk={handleAuditOk}
        onCancel={() => {
          setAuditModalVisible(false);
          setSelectedAbility(null);
        }}
        form={auditForm}
        ability={selectedAbility}
        userInfo={userInfo}
      />
    </div>
  );
};

export default Abilities;
